package com.efounder.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import com.efounder.chat.R;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.model.AppConstant;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.chat.view.RingProgressBar;
import com.efounder.chat.view.SendImgProgressView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.ToastUtil;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.LoopingMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.utilcode.util.StatusBarUtil;

import org.apache.tools.ant.util.FileUtils;

import java.io.File;

import static android.view.View.VISIBLE;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 联信视频播放
 */
public class PlayerActivity extends Activity {
    static String sdDir = null;
    private static final String TAG = "PlayerActivity";
    //是否停止播放
    private static boolean isStop = false;
    //是否正在下载
    private boolean isDowning = false;

    static {

        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory().toString();//获取根目录
        } else {
            sdDir = Environment.getRootDirectory().toString();
        }
    }

    // SimpleExoPlayer使用参考  https://blog.csdn.net/dengpeng_/article/details/54910840
    //https://www.jianshu.com/p/d5a0ed770b3d
    //https://blog.csdn.net/ctianju/article/details/79239607
    private SimpleExoPlayer player;
    private TrackSelector trackSelector;
    private View mCloseBtnView;
    private View mProgressBarView;
    private SendImgProgressView progressBar;
//    private ProgressBar progressBar1;
    private RingProgressBar progressBar2;
    //文件下载路径
    private String fileDownDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        isStop = false;
        initView();
        initData();
    }

    private void initView() {
        StatusBarUtil.setColor(this, Color.parseColor("#000000"));
        mCloseBtnView = findViewById(R.id.video_close_view);
        FrameLayout close = (FrameLayout) findViewById(R.id.video_close_view);
        mProgressBarView = findViewById(R.id.progressbar);
        progressBar = findViewById(R.id.progressView);
//        progressBar1 = findViewById(R.id.progressbar1);
        progressBar2 = findViewById(R.id.progress_bar2);

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null && player.getPlayWhenReady() == false) {
            player.setPlayWhenReady(true);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        pausePlayer();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isStop = true;
        //停止下载
        if (isDowning) {
            JFCommonRequestManager.getInstance(this).cannelOkHttpRequest(TAG);
            FileUtils.delete(new File(fileDownDir));
        }

        releasePlayer();
    }

    private void initData() {
        Intent intent = getIntent();

        String videoName = intent.getStringExtra("videoName");
        String videoPath = intent.getStringExtra("videoPath");

        if (intent.hasExtra("localFilePath")) {
            //本地文件
            String localFilePath = intent.getStringExtra("localFilePath");
            if (new File(localFilePath).exists()) {
                initPlayer(localFilePath);
            }
            return;
        }

        //为了兼容之前的 手机录制的 videoname 是 record 开头
        String filepath = ImageUtil.videopath + videoName;

        if (new File(filepath).exists()) {
            initPlayer(filepath);
        } else {
//            别人发布的视频下载到本地
            downloadVideo(videoPath);
            showProgressView(false);
            setCloseButton(false);
        }
    }


    /**
     * 显示关闭视频的按钮
     *
     * @param isShow isShow
     */
    private void setCloseButton(boolean isShow) {
        mCloseBtnView.setVisibility(isShow ? VISIBLE : View.INVISIBLE);
    }

    /**
     * 显示loading圈
     *
     * @param isTransparentBg isTransparentBg
     */
    private void showProgressView(Boolean isTransparentBg) {
        mProgressBarView.setVisibility(VISIBLE);
        if (!isTransparentBg) {
            mProgressBarView.setBackgroundResource(android.R.color.black);
        } else {
            mProgressBarView.setBackgroundResource(android.R.color.transparent);
        }
    }

    /**
     * 下载视频
     *
     * @param videoPath 视屏地址url
     */
    private void downloadVideo(final String videoPath) {
        isDowning = true;
        final String videoName = PansoftCloudUtil.getPansoftCloudFileId(videoPath);

        fileDownDir = AppConstant.APP_ROOT + "/" + EnvironmentVariable.getProperty(CHAT_USER_ID) + "/chat/chatvideo";
        final String fileDownLoadPath = fileDownDir + "/" + videoName;
        JFCommonRequestManager.getInstance(this).downLoadFile(TAG, videoPath, videoName,
                fileDownDir, new JFCommonRequestManager.ReqProgressCallBack<Object>() {
                    @Override
                    public void onProgress(long total, long current) {
                        if (isStop) {
                            return;
                        }
                        // progressBar.setProgress((int) (current / total * 100));
                        // progressBar1.setProgress((int) (current / total * 100));
                        Log.i(TAG, current + "   " + total);
                        int progress = (int) (current * 100L / total);  //下载进度
                        progressBar2.setProgress(progress);
                    }

                    @Override
                    public void onReqSuccess(Object result) {
                        if (isStop) {
                            return;
                        }
                        isDowning = false;
                        mProgressBarView.setVisibility(View.GONE);
                        initPlayer(fileDownLoadPath);
                        setCloseButton(true);
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        FileUtils.delete(new File(fileDownLoadPath));
                        if (isStop) {
                            return;
                        }
                        isDowning = false;
                        mProgressBarView.setVisibility(View.GONE);
                        ToastUtil.showToast(PlayerActivity.this, R.string.wrchatview_video_upload_fail);
                    }
                });

    }

    private void initPlayer(String filepath) {
//
//        try {
//            //Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MICRO_KIND);
//            Bitmap bitmap = ImageUtil.getVideoThumbnail(filepath);
//            //通过url截取文件名
//            String fileName = videlUrl.substring(0, videlUrl.lastIndexOf("/"));
//            String videoName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
//            if (bitmap != null)
//                ImageUtil.saveCacheVideoThumbnail(bitmap, videoName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        SimpleExoPlayerView simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
        // todo 1.创建一个默认TrackSelector
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

        //todo2. 创建播放器
        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
        simpleExoPlayerView.setPlayer(player);

// Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, "OSP Application"), bandwidthMeter);
// Produces Extractor instances for parsing the media data.
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
// This is the MediaSource representing the media to be played.
//        String filepath = sdDir + "/OSPMobileLiveApp" + "/2967/chat/chatvideo/1499307856384.mp4";
//        String filepath = sdDir+"/OSPMobileLiveApp"+"/2967/chat/chatvideo/1499312193963.mov";
        Uri mp4VideoUri = Uri.parse(filepath);
        final MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri,
                dataSourceFactory, extractorsFactory, null, null);
        /**
         * 默认循环2147483647
         */
        LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
// Prepare the player with the source.
        player.prepare(loopingSource, true, true);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        player.setPlayWhenReady(true);
        /*if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){//竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }*/

        //todo 这段代码是屏蔽 控制界面的 yqs 20180520
//        View chiild0 = simpleExoPlayerView.getChildAt(1);
//        if (chiild0 != null) {
//            View childAt = ((ViewGroup) chiild0).getChildAt(0);
//            if (childAt != null) {
//                childAt.setVisibility(View.GONE);
//            }
//
//        }
//        View child0 = simpleExoPlayerView.getChildAt(0);
//        if (child0 != null) {
//            child0.setBackgroundColor(Color.parseColor("#000000"));
//        }
        player.setPlayWhenReady(true);
    }


    /**
     * 重置
     */
    private void releasePlayer() {
        if (player != null) {
//            debugViewHelper.stop();
//            debugViewHelper = null;
//            shouldAutoPlay = player.getPlayWhenReady();
//            updateResumePosition();
            player.release();
            player = null;
            trackSelector = null;
//            trackSelectionHelper = null;
//            eventLogger = null;
        }
    }

    /**
     * 暂停播放
     */
    private void pausePlayer() {
        if (player != null) {
            player.setPlayWhenReady(false);
        }
    }

}
